package com.ruoyi.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.util.AsyncUploadService;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.Partyclass;
import com.ruoyi.service.IPartyclassService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * partyclassController
 * 
 * @author ya
 * @date 2025-07-11
 */
@RestController
@RequestMapping("/partyclass/partyclass")
public class PartyclassController extends BaseController
{
    @Autowired
    private IPartyclassService partyclassService;

    @Autowired
    private AsyncUploadService asyncUploadService;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 查询partyclass列表
     */
//    @PreAuthorize("@ss.hasPermi('partyclass:partyclass:list')")
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(Partyclass partyclass)
    {
        startPage();
        List<Partyclass> list = partyclassService.selectPartyclassList(partyclass);
        return getDataTable(list);
    }


    /**
     * 发布视频
     */
    @PutMapping("/publish/{id}")
    public AjaxResult publish(@PathVariable("id") Long id){
        Partyclass partyclass = partyclassService.getById(id);
        if(partyclass == null){
            return AjaxResult.error("视频不存在");
        }
        if(Objects.equals(partyclass.getPublish(), 1)){
            partyclass.setPublish(0);
            partyclassService.updateById(partyclass);
            return AjaxResult.success("取消发布成功");
        }
        partyclass.setPublish(1);
        partyclassService.updateById(partyclass);
        return AjaxResult.success("发布成功");
    }
    /**
     * 根据视频栏目查询数据
     */
    @Anonymous
    @GetMapping("/listByVideoType/{video_type}")
    public TableDataInfo listByVideoType(@PathVariable("video_type") int type)
    {
        return getDataTable(partyclassService.selectPartyclassByType(type));
    }



    /**
     * 导出partyclass列表
     */
    @PreAuthorize("@ss.hasPermi('partyclass:partyclass:export')")
    @Log(title = "partyclass", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Partyclass partyclass)
    {
        List<Partyclass> list = partyclassService.selectPartyclassList(partyclass);
        ExcelUtil<Partyclass> util = new ExcelUtil<Partyclass>(Partyclass.class);
        util.exportExcel(response, list, "partyclass数据");
    }

    /**
     * 获取partyclass详细信息
     */
//    @PreAuthorize("@ss.hasPermi('partyclass:partyclass:query')")
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(partyclassService.selectPartyclassById(id));
    }

    /**
     * 删除partyclass
     */
    @PreAuthorize("@ss.hasPermi('partyclass:partyclass:remove')")
    @Log(title = "partyclass", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(partyclassService.deletePartyclassByIds(ids));
    }

    /**
     * 新增partyclass
     */
    //@PreAuthorize("@ss.hasPermi('partyclass:partyclass:add')")
    @Anonymous
    @Log(title = "partyclass", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestParam(value = "name",required = false) String name,
                          @RequestParam(value = "file",required = false) MultipartFile file,
                          @RequestParam(value = "cover_img",required = false) MultipartFile coverImg,
                          @RequestParam(value = "x",required = false) Double x,
                          @RequestParam(value = "y",required = false) Double y,
                          @RequestParam(value = "pubdate",required = false) String pubdate,
                          @RequestParam(value = "author",required = false) String author,
                          @RequestParam(value = "video_origin",required = false) String videoOrigin,
                          @RequestParam(value = "type",required = false) int type
    )
    {
        System.out.println("=== 接收到文件上传请求 ===");
        System.out.println("name: " + name);
        System.out.println("file is null: " + (file == null));
        System.out.println("file is empty: " + (file != null ? file.isEmpty() : "N/A"));
        System.out.println("coverImg is null: " + (coverImg == null));
        System.out.println("coverImg is empty: " + (coverImg != null ? coverImg.isEmpty() : "N/A"));
        if (file != null && !file.isEmpty()) {
            System.out.println("file original name: " + file.getOriginalFilename());
            System.out.println("file size: " + file.getSize());
        }
        if (coverImg != null && !coverImg.isEmpty()) {
            System.out.println("coverImg original name: " + coverImg.getOriginalFilename());
            System.out.println("coverImg size: " + coverImg.getSize());
        }
        
        Partyclass partyclass = new Partyclass();
        if (name != null) partyclass.setName(name);
        if (x != null) partyclass.setX(x);
        if (y != null) partyclass.setY(y);
        if (pubdate != null) partyclass.setPubdate(pubdate);
        if (author != null) partyclass.setAuthor(author);
        if (videoOrigin != null) partyclass.setVideoOrigin(videoOrigin);
        partyclass.setType(type);
        
        // 设置默认排序值为该类型下的最大值+1
        int maxSortOrder = partyclassService.selectMaxSortOrderByType(type);
        partyclass.setSortOrder(maxSortOrder + 1);
        
        //先保存基本信息获取ID
        partyclassService.insertPartyclass(partyclass);

        System.out.println("插入的数据:"+partyclass);
        
        // 获取刚插入记录的ID
        Long insertedId = partyclass.getId();
        if (insertedId == null) {
            return AjaxResult.error("创建记录失败");
        }
        
        // 重新查询获取完整信息
        Partyclass insertedPartyclass = partyclassService.selectPartyclassById(insertedId);
        System.out.println("insertedPartyclass type: " + insertedPartyclass.getType());
        System.out.println("insertedPartyclass sortOrder: " + insertedPartyclass.getSortOrder());


        boolean hasFile = (file != null && !file.isEmpty());
        boolean hasCoverImg = (coverImg != null && !coverImg.isEmpty());
        
        if (hasFile) {
            //有视频文件上传时使用异步上传
            try {
                byte[] fileBytes = file.getBytes();
                asyncUploadService.asyncUploadPartyFile(insertedPartyclass, fileBytes, file.getOriginalFilename());
            } catch (Exception e) {
                return AjaxResult.error("上传视频文件失败");
            }
        }
        
        if (hasCoverImg) {
            //封面图片也使用异步上传
            try {
                byte[] coverBytes = coverImg.getBytes();
                asyncUploadService.asyncUploadPartyCoverImg(insertedPartyclass, coverBytes, coverImg.getOriginalFilename());
            } catch (Exception e) {
                return AjaxResult.error("上传封面图片失败: " + e.getMessage());
            }
        }
        
        if (hasFile || hasCoverImg) {
            // 返回上传任务信息和ID
            return AjaxResult.success(insertedPartyclass);
        } else {
            //没有文件时直接保存数据
            return success("新增成功");
        }
    }

    /**
     * 修改partyclass
     */
    //@PreAuthorize("@ss.hasPermi('partyclass:partyclass:edit')")
    @Anonymous
    @Log(title = "partyclass", businessType = BusinessType.UPDATE)
    @PutMapping("/update/{id}")
    public AjaxResult edit(@PathVariable Long id,
                           @RequestParam(value = "name",required = false)String name,
                           @RequestParam(value = "file",required = false)MultipartFile file,
                           @RequestParam(value = "cover_img",required = false)MultipartFile coverImg,
                           @RequestParam(value = "pubdate",required = false) String pubdate,
                           @RequestParam(value = "author",required = false) String author,
                           @RequestParam(value = "video_origin",required = false) String videoOrigin,
                           @RequestParam(value = "type",required = false) int type,
                           @RequestParam(value = "x",required = false) Double x,
                           @RequestParam(value = "y",required = false) Double y
    )
    {
        System.out.println("=== 接收到文件更新请求 ===");
        System.out.println("id: " + id);
        System.out.println("name: " + name);
        System.out.println("file is null: " + (file == null));
        System.out.println("file is empty: " + (file != null ? file.isEmpty() : "N/A"));
        System.out.println("coverImg is null: " + (coverImg == null));
        System.out.println("coverImg is empty: " + (coverImg != null ? coverImg.isEmpty() : "N/A"));
        if (file != null && !file.isEmpty()) {
            System.out.println("file original name: " + file.getOriginalFilename());
            System.out.println("file size: " + file.getSize());
        }
        if (coverImg != null && !coverImg.isEmpty()) {
            System.out.println("coverImg original name: " + coverImg.getOriginalFilename());
            System.out.println("coverImg size: " + coverImg.getSize());
        }
        
        Partyclass partyclass = partyclassService.selectPartyclassById(id);
        if (partyclass==null) return AjaxResult.error("记录不存在");
        if (name != null) partyclass.setName(name);
        if (pubdate != null) partyclass.setPubdate(pubdate);
        if (author != null) partyclass.setAuthor(author);
        if (videoOrigin != null) partyclass.setVideoOrigin(videoOrigin);
        if (x != null) partyclass.setX(x);
        if (y != null) partyclass.setY(y);
        partyclass.setType(type);

        //同步处理数据
        boolean hasFile = (file != null && !file.isEmpty());
        boolean hasCoverImg = (coverImg != null && !coverImg.isEmpty());
        
        //先更新基本信息
        partyclassService.updatePartyclass(partyclass);
        
        if (hasFile) {
            //有视频文件上传时使用异步上传
            try {
                byte[] fileBytes = file.getBytes();
                asyncUploadService.asyncUploadPartyFile(partyclass, fileBytes, file.getOriginalFilename());
            } catch (Exception e) {
                return AjaxResult.error("上传视频文件失败");
            }
        }
        
        if (hasCoverImg) {
            //封面图片也使用异步上传
            try {
                byte[] coverBytes = coverImg.getBytes();
                asyncUploadService.asyncUploadPartyCoverImg(partyclass, coverBytes, coverImg.getOriginalFilename());
            } catch (Exception e) {
                return AjaxResult.error("上传封面图片失败: " + e.getMessage());
            }
        }
        
        if (hasFile || hasCoverImg) {
            // 返回上传任务信息
            return AjaxResult.success("已提交上传任务，请等待完成").put("data", partyclass);
        } else {
            //没有文件时直接保存数据
            return success("修改成功");
        }
    }

    /**
     * 交换两个partyclass的排序值
     */
    @Anonymous
    @Log(title = "partyclass", businessType = BusinessType.UPDATE)
    @PutMapping("/swapSortOrder")
    public AjaxResult swapSortOrder(@RequestBody Map<String, Long> payload) {
        Long id1 = payload.get("id1");
        Long id2 = payload.get("id2");
        
        if (id1 == null || id2 == null) {
            return AjaxResult.error("参数错误");
        }
        
        // 获取两个记录
        Partyclass partyclass1 = partyclassService.selectPartyclassById(id1);
        Partyclass partyclass2 = partyclassService.selectPartyclassById(id2);
        
        if (partyclass1 == null || partyclass2 == null) {
            return AjaxResult.error("记录不存在");
        }
        
        // 确保两个记录属于同一类型
        if (partyclass1.getType() != partyclass2.getType()) {
            return AjaxResult.error("只能在同一类型内调整排序");
        }
        
        // 交换排序值
        Integer tempSortOrder = partyclass1.getSortOrder();
        partyclass1.setSortOrder(partyclass2.getSortOrder());
        partyclass2.setSortOrder(tempSortOrder);
        
        // 更新数据库
        partyclassService.updatePartyclass(partyclass1);
        partyclassService.updatePartyclass(partyclass2);
        
        return success("排序更新成功");
    }
    
    /**
     * 将指定记录移动到顶部
     */
    @Anonymous
    @Log(title = "partyclass", businessType = BusinessType.UPDATE)
    @PutMapping("/moveToTop/{id}")
    public AjaxResult moveToTop(@PathVariable Long id) {
        // 获取记录
        Partyclass targetPartyclass = partyclassService.selectPartyclassById(id);
        
        if (targetPartyclass == null) {
            return AjaxResult.error("记录不存在");
        }
        
        int targetType = targetPartyclass.getType();
        int currentSortOrder = targetPartyclass.getSortOrder();
        
        // 将该类型下所有排序值小于当前记录的记录都加1
        partyclassService.incrementSortOrderForTypeLessThan(targetType, currentSortOrder);
        
        // 将目标记录的排序值设为0（最前）
        targetPartyclass.setSortOrder(0);
        partyclassService.updatePartyclass(targetPartyclass);
        
        return success("已移至顶部");
    }
    
    /**
     * 将指定记录上移一位
     */
    @Anonymous
    @Log(title = "partyclass", businessType = BusinessType.UPDATE)
    @PutMapping("/moveUp/{id}")
    public AjaxResult moveUp(@PathVariable Long id) {
        // 获取记录
        Partyclass targetPartyclass = partyclassService.selectPartyclassById(id);
        
        if (targetPartyclass == null) {
            return AjaxResult.error("记录不存在");
        }
        
        int targetType = targetPartyclass.getType();
        int currentSortOrder = targetPartyclass.getSortOrder();
        
        // 查找排序值刚好小于当前记录的记录
        Partyclass previousPartyclass = partyclassService.selectPreviousPartyclass(targetType, currentSortOrder);
        
        if (previousPartyclass == null) {
            return AjaxResult.error("已经是第一个了");
        }
        
        // 交换排序值
        Integer tempSortOrder = targetPartyclass.getSortOrder();
        targetPartyclass.setSortOrder(previousPartyclass.getSortOrder());
        previousPartyclass.setSortOrder(tempSortOrder);
        
        // 更新数据库
        partyclassService.updatePartyclass(targetPartyclass);
        partyclassService.updatePartyclass(previousPartyclass);
        
        return success("上移成功");
    }
    
    /**
     * 将指定记录下移一位
     */
    @Anonymous
    @Log(title = "partyclass", businessType = BusinessType.UPDATE)
    @PutMapping("/moveDown/{id}")
    public AjaxResult moveDown(@PathVariable Long id) {
        // 获取记录
        Partyclass targetPartyclass = partyclassService.selectPartyclassById(id);
        
        if (targetPartyclass == null) {
            return AjaxResult.error("记录不存在");
        }
        
        int targetType = targetPartyclass.getType();
        int currentSortOrder = targetPartyclass.getSortOrder();
        
        // 查找排序值刚好大于当前记录的记录
        Partyclass nextPartyclass = partyclassService.selectNextPartyclass(targetType, currentSortOrder);
        
        if (nextPartyclass == null) {
            return AjaxResult.error("已经是最后一个了");
        }
        
        // 交换排序值
        Integer tempSortOrder = targetPartyclass.getSortOrder();
        targetPartyclass.setSortOrder(nextPartyclass.getSortOrder());
        nextPartyclass.setSortOrder(tempSortOrder);
        
        // 更新数据库
        partyclassService.updatePartyclass(targetPartyclass);
        partyclassService.updatePartyclass(nextPartyclass);
        
        return success("下移成功");
    }
}
